package com.realshare.frame.core.config;

import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * ${DESCRIPTION}
 *
 * @author realshare
 * @email 15075107780@139.com
 * @create 2018-08-02 21:51
 * @modify 2018-08-02 21:51
 **/
@Configuration
public class DataSourceConfig {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //配置默认主数据源
    @Bean(name = "masterDatasource")
    public DataSource getDataSource(Environment env) {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
        ds.setUsername(env.getProperty("spring.datasource.username"));
        ds.setPassword(env.getProperty("spring.datasource.password"));
        ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        return ds;
    }

    //配置第二个查询从数据源
    /*@Bean(name = "slaveQueryDatasource")
    public DataSource getQueryDataSource(Environment env) {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(env.getProperty("spring.query.datasource.url"));
        ds.setUsername(env.getProperty("spring.query.datasource.username"));
        ds.setPassword(env.getProperty("spring.query.datasource.password"));
        ds.setDriverClassName(env.getProperty("spring.query.datasource.driver-class-name"));
        return ds;
    }*/

    //主从数据库配置
    /*@Bean
    public BeetlSqlDataSource beetlSqlDataSource(@Qualifier("masterDatasource") DataSource master
            , @Qualifier("slaveQueryDatasource") DataSource slave) {
        BeetlSqlDataSource source = new BeetlSqlDataSource();
        source.setMasterSource(master);
        source.setSlaves(new DataSource[]{slave});
        return source;
    }*/

    //开启主数据库事务
    @Bean(name = "transactionManagerMaster")
    public DataSourceTransactionManager getMasterTransactionManager(@Qualifier("masterDatasource") DataSource master) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(master);
        return dsm;
    }

    //开启从数据库事务
    /*@Bean(name = "transactionManagerSlave")
    public DataSourceTransactionManager getSlaveTransactionManager(@Qualifier("slaveQueryDatasource") DataSource slave) {
        DataSourceTransactionManager dsm = new DataSourceTransactionManager();
        dsm.setDataSource(slave);
        return dsm;
    }*/

}
